package com.heima.article.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.service.ApArticleFreemarkerService;
import com.heima.article.service.ApArticleService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.search.pojos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.BeanUtils;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;

import static com.heima.common.constants.ArticleConstants.ARTICLE_SYNC_ES_TOPIC;

@Service
@Async
@Transactional
public class ApArticleFreemarkerImpl implements ApArticleFreemarkerService {
    @Resource
    private Configuration configuration;
    @Resource
    private FileStorageService fileStorageService;
    @Resource
    private ApArticleService apArticleService;
    @Resource
    private KafkaTemplate<String, String> kafkaTemplate;

    @Override
    public void buildArticleToMinIo(ApArticle apArticle, String content) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("content", JSONArray.parseArray(content));

        try {
            Template template = configuration.getTemplate("article.ftl");
            StringWriter out = new StringWriter();
            template.process(map, out);

            ByteArrayInputStream in = new ByteArrayInputStream(out.toString().getBytes());
            String url = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", in);

            creatESIndex(apArticle, content, url);
            apArticleService.update(Wrappers.<ApArticle>lambdaUpdate().eq(ApArticle::getId, apArticle.getId()).set(ApArticle::getStaticUrl, url));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }

    private void creatESIndex(ApArticle apArticle, String content, String url) {
        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle, vo);
        vo.setContent(content);
        vo.setStaticUrl(url);
        kafkaTemplate.send(ARTICLE_SYNC_ES_TOPIC, JSON.toJSONString(vo));
    }
}
